<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
// use Illuminate\Database\Eloquent\SoftDeletes;  // 注释掉，因为 deleted_at 是 int 类型

class Vendor extends Model
{
    use HasFactory;
    // 不使用 SoftDeletes trait，因为数据库的 deleted_at 是 int 类型，不是 timestamp

    protected $table = 'ims_yz_vendor';

    protected $fillable = [
        'uniacid',
        'supplier_name',
        'mobile',
        'status',
        'created_at',
        'updated_at',
        'applicant_id',
        'real_name',
        'referrer_id',
        'province_id',
        'city_id',
        'district_id',
        'address',
        'platform_id'
    ];

    protected $casts = [
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'deleted_at' => 'integer'  // 注意：数据库中 deleted_at 是 int 类型，不是 timestamp
    ];

    /**
     * 重写软删除查询，处理 deleted_at 为 0 的情况
     */
    protected static function boot()
    {
        parent::boot();
        
        static::addGlobalScope('deleted_at_scope', function ($query) {
            // 处理 deleted_at 为 0 的情况，将其视为未删除
            $query->where(function($q) {
                $q->whereNull('deleted_at')
                  ->orWhere('deleted_at', 0);
            });
        });
    }

    // 关联地址信息
    public function province()
    {
        return $this->belongsTo(Address::class, 'province_id');
    }

    public function city()
    {
        return $this->belongsTo(Address::class, 'city_id');
    }

    public function district()
    {
        return $this->belongsTo(Address::class, 'district_id');
    }

    // 关联申请人
    public function applicant()
    {
        return $this->belongsTo(User::class, 'applicant_id');
    }

    // 关联推荐人
    public function referrer()
    {
        return $this->belongsTo(User::class, 'referrer_id');
    }

    // 获取完整地址
    public function getFullAddressAttribute()
    {
        $address = '';
        
        if ($this->province) {
            $address .= $this->province->areaname . ' ';
        }
        if ($this->city) {
            $address .= $this->city->areaname . ' ';
        }
        if ($this->district) {
            $address .= $this->district->areaname . ' ';
        }
        if ($this->address) {
            $address .= $this->address;
        }
        
        return trim($address) ?: '请填写详细地址';
    }
}